<template>
  <div class="import-dialog">
    <el-dialog v-model="isDialogImport" width="720" :align-center="true" destroy-on-close @closed="resetCheck">
      <template #header>
        <title-view title="导入"></title-view>
      </template>
      <div v-loading="uploadLoading">
        <el-upload
          class="upload-demo"
          accept=".xls,.xlsx"
          :http-request="uploadData"
          :drag="fileListData.length == 0 ? true : false"
          :limit="1"
          :auto-upload="false"
          :file-list="fileListData"
          :on-change="handleChange"
          :before-upload="beforeUpload"
          :show-file-list="false"
        >
          <template #trigger>
            <div v-if="fileListData.length == 0">
              <svg-icon iconClass="cloud-import" style="font-size: 50px" />
              <div class="upload-text">上传文件</div>
              <div class="upload-format">也可以拖拽到此处上传（支持格式xls、xlsx）</div>
            </div>
          </template>
        </el-upload>
        <div class="file-list" v-if="fileListData.length > 0">
          <div class="file-item" v-for="item in fileListData" :key="item.uid">
            <div class="file-name">
              <div class="left">
                <el-icon style="padding: 0px 10px" color="#007dff">
                  <Document />
                </el-icon>
                {{ item.name }}
              </div>
            </div>
            <div class="delete-icon" @click="deleteFile">
              <el-icon>
                <Delete />
              </el-icon>
            </div>
          </div>
        </div>
        <div class="error-msg" v-if="errMsgArr.length > 0">
          <span v-for="errItem in errMsgArr">{{ errItem }}</span
          ><br />
        </div>
        <div class="upload-tips" @click="downloadTemplate">
          <svg-icon iconClass="cloud-export" style="font-size: 24px; margin-right: 5px" />
          下载模板导入表格
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isDialogImport = false" :disabled="uploadLoading">取消</el-button>
          <el-button type="primary" @click="submitUpload" :disabled="uploadLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, getCurrentInstance, ref } from "vue";
import { Delete, Document } from "@element-plus/icons-vue";
import { importTemplate, importCrmconfirm, customerImport, checkImportStatus } from "@/apis/clientManager";
import { documentFlow } from "@/utils/downFile";
import { ElMessageBox } from "element-plus";

const { proxy } = getCurrentInstance();
const emit = defineEmits(["update:modelValue", "importConfirm"]);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
});

const isDialogImport = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    emit("update:modelValue", val);
  }
});

//导入
const uploadLoading = ref(false);
const errMsgArr = ref([]);
const fileListData = ref([]);
const handleChange = (file, fileList) => {
  fileListData.value = fileList;
};
const uploadData = () => {};
const submitUpload = () => {
  if (fileListData.value.length == 0) return;
  uploadLoading.value = true;
  let upData = new FormData();
  upData.append("file", fileListData.value[0].raw);
  customerImport(upData)
    .then(res => {
      uploadLoading.value = false;
      const isErrMsg = res.data?.iserrMsg;
      const idDuplicateData = res.data?.idDuplicateData;
      if (!isErrMsg) {
        errMsgArr.value = res.data?.list ?? [];
      } else if (idDuplicateData) {
        ElMessageBox.confirm(res.data.errMsg)
          .then(() => {
            uploadLoading.value = true;
            repeatUploadData(res.data?.importToken);
          })
          .catch(() => {
            // catch error
            uploadLoading.value = false;
            fileListData.value.forEach(item => {
              item.status = "ready";
            });
          });
      } else {
        checking(res.data.importToken);
      }
    })
    .catch(err => {
      errMsgArr.value = [err.message];
      uploadLoading.value = false;
    });
};

let delayTime = 1000;
let count = 0;
function checking(importsToken) {
  setTimeout(
    () => {
      count++;
      checkImportStatus(importsToken).then(res => {
        if (res.data) {
          setTimeout(() => {
            proxy.$modal.msgSuccess("导入成功");
          }, 2000);
          setTimeout(() => {
            uploadLoading.value = false;
            emit("importConfirm");
          }, 4000);
        } else {
          checking(importsToken);
        }
      });
    },
    delayTime * (2 * count - 2)
  );
}

const repeatUploadData = importsToken => {
  importCrmconfirm(importsToken).then(res => {
    checking(importsToken);
    // proxy.$modal.msgSuccess("导入成功");
    // uploadLoading.value = false;
    // setTimeout(() => {
    //   emit("importConfirm");
    // }, 2000);
  });
};

const deleteFile = () => {
  fileListData.value = [];
  errMsgArr.value = [];
};

//上传格式校验
const getSuffix = fileName => {
  return fileName.slice(fileName.lastIndexOf(".") + 1);
};
const beforeUpload = fileItem => {
  const suffix = ["xls", "xlsx"];
  if (fileItem.name && !suffix.includes(getSuffix(fileItem.name))) {
    proxy.$modal.msgSuccess("请上传xls、xlsx文件！");
    return false;
  }
  return true;
};

//下载模板
const downloadTemplate = async () => {
  const res = await importTemplate();
  documentFlow(res, "下载模板", "xlsx");
};
</script>

<style scoped lang="scss">
.import-dialog {
  :deep(.el-upload-dragger) {
    background: #eaecf0;
    border-color: #c0c4cc;
  }
  .upload-text {
    color: #007dff;
    font-size: 14px;
    margin: 15px 0px;
  }
  .upload-format {
    font-size: 14px;
    color: #86909c;
  }
  .upload-tips {
    display: flex;
    align-items: center;
    font-size: 18px;
    margin-top: 20px;
    color: #007dff;
    cursor: pointer;
  }
  .dialog-footer {
    margin-top: 20px;
    position: relative;
    button {
      width: 90px;
      height: 38px;
    }
    &:before {
      content: "";
      width: calc(100% + 40px);
      height: 1px;
      transform: scaleY(50%);
      left: -20px;
      top: -20px;
      background: #c2d4e8;
      position: absolute;
    }
  }
  .file-list {
    .file-item {
      display: flex;
      //justify-content: space-between;
      align-items: center;
      height: 36px;
      font-size: 14px;
      color: #121314;
      .file-name {
        background: #fafafa;
        width: calc(100% - 50px);
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .left {
          display: flex;
          align-items: center;
        }
      }
      .delete-icon {
        width: 50px;
        text-align: center;
        cursor: pointer;
      }
    }
  }
  .error-msg {
    color: red;
    font-size: 14px;
    margin-top: 10px;
  }
}
</style>
